# @file    : test
# @time    : 2025/4/17
# @author  : yongpeng.yao
# @desc    :
import base64
import hashlib
import hmac
import json
import time
from pathlib import Path

import requests


def convert_file_to_base64(file_path):
    """
    将图片转换为base64编码
    :param file_path: 图片路径
    :return: base64编码
    """
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read())
    return encoded_string.decode("utf-8")


APP_ID = '20221122001464331'
SECRET_KEY = 'SerbodwPCAiL2Zwm0PZv'


class TranslateException(Exception):
    pass


# 调用 百度文档翻译API接口 进行翻译
def baidu_translate_create_job(file_path, from_lang='jp', to_lang='zh'):
    """
    调用 百度文档翻译API接口 上传文件 返回文件id
    :param file_path: 文档目录
    :param from_lang: 源语言，默认为日语
    :param to_lang: 目标语言，默认为中文
    :return: 文件id
    """
    quote_base_url = 'https://fanyi-api.baidu.com/transapi/doctrans/createjob/quote'
    x_timestamp = str(int(time.time()))
    headers = {
        'Content-Type': 'application/json',
        'X-Appid': APP_ID,
        'X-Sign': "",
        'X-Timestamp': x_timestamp
    }

    # 判断文件是否存在
    file_path_obj = Path(file_path)
    if not file_path_obj.exists() or not file_path_obj.is_file():
        raise FileNotFoundError("文件不存在")
    # 获取文件名和后缀
    file_name, file_ext = file_path_obj.name, file_path_obj.suffix
    json_data = {
        "from": from_lang,
        "to": to_lang,
        "input": {
            "content": "",
            "format": file_ext[1:],
            "filename": file_name,
            "transImage": 0
        }
    }
    # 对文档进行base64编码
    file_b64 = convert_file_to_base64(file_path)
    json_data["input"]["content"] = file_b64

    # Step1: 传入http请求中的body（原始json串，保留原始格式）字符串作为字符串1。（注意部分语言需确保字符串为UTF-8编码）
    # Step2. 将 APPID(X-Appid)，时间戳(X-Timestamp)， 字符串1，按照APPID+时间戳+字符串1顺序拼接得到字符串2。
    # Step3. 对字符串2 做hmac_sha256加密，密钥使用平台分配的密钥(可在管理控制台查看) 得到字符串3。
    # Step4. 对字符串3 做base64编码得到X-Sign。
    sign_str = f"{APP_ID}{x_timestamp}{json.dumps(json_data)}"
    headers['X-Sign'] = base64.b64encode(
        hmac.new(SECRET_KEY.encode(), sign_str.encode(), hashlib.sha256).digest()).decode()

    response = requests.post(quote_base_url, headers=headers, json=json_data)
    if response.status_code != 200:
        raise TranslateException("百度翻译API请求失败")
    result = response.json()
    if result['code'] != 0:
        raise TranslateException("百度翻译API请求失败")
    return result['data']['fileId']


def baidu_query_quote(file_id):
    while True:
        query_quote_url = "https://fanyi-api.baidu.com/transapi/doctrans/query/quote"
        x_timestamp = str(int(time.time()))
        headers = {
            'Content-Type': 'application/json',
            'X-Appid': APP_ID,
            'X-Sign': "",
            'X-Timestamp': x_timestamp
        }
        json_data = {"fileId": file_id}
        sign_str = f"{APP_ID}{x_timestamp}{json.dumps(json_data)}"
        headers['X-Sign'] = base64.b64encode(
            hmac.new(SECRET_KEY.encode(), sign_str.encode(), hashlib.sha256).digest()).decode()
        response = requests.post(query_quote_url, headers=headers, json=json_data)
        if response.status_code != 200:
            raise TranslateException("百度翻译API请求失败")
        result = response.json()
        if result['code'] != 0:
            raise TranslateException("百度翻译API请求失败")
        if result['data']['status'] == 1:
            print("翻译完成")
            if result['data']['amount'] > 100:  # 超过1元
                print('超过1元，请充值！！!')
                return False
            return True
        elif result['data']['status'] == 2:
            print("翻译失败")
            return False
        else:
            print("翻译中，请稍等...")
            time.sleep(5)


def execute_tran(file_path, file_id, from_lang='jp', to_lang='zh'):
    tran_url = 'https://fanyi-api.baidu.com/transapi/doctrans/createjob/trans'
    x_timestamp = str(int(time.time()))
    headers = {
        'Content-Type': 'application/json',
        'X-Appid': APP_ID,
        'X-Sign': "",
        'X-Timestamp': x_timestamp
    }
    # 判断文件是否存在
    file_path_obj = Path(file_path)
    if not file_path_obj.exists() or not file_path_obj.is_file():
        raise FileNotFoundError("文件不存在")
    # 获取文件名和后缀
    file_name, file_ext = file_path_obj.name, file_path_obj.suffix
    json_data = {
        "from": from_lang,
        "to": to_lang,
        "input": {
            "fileId": file_id,
            "format": file_ext[1:],
            "filename": file_name,
            "transImage": 0
        },
        "output": {
            "format": file_ext[1:]
        }
    }
    sign_str = f"{APP_ID}{x_timestamp}{json.dumps(json_data)}"
    headers['X-Sign'] = base64.b64encode(
        hmac.new(SECRET_KEY.encode(), sign_str.encode(), hashlib.sha256).digest()).decode()
    response = requests.post(tran_url, headers=headers, json=json_data)
    if response.status_code != 200:
        raise TranslateException("百度翻译API请求失败")
    result = response.json()
    if result['code'] != 0:
        raise TranslateException("百度翻译API请求失败")
    return result['data']['requestId']


def query_trans(request_id):
    query_trans_url = 'https://fanyi-api.baidu.com/transapi/doctrans/query/trans'
    while True:
        x_timestamp = str(int(time.time()))
        headers = {
            'Content-Type': 'application/json',
            'X-Appid': APP_ID,
            'X-Sign': "",
            'X-Timestamp': x_timestamp
        }
        json_data = {
            "requestId": request_id
        }
        sign_str = f"{APP_ID}{x_timestamp}{json.dumps(json_data)}"
        headers['X-Sign'] = base64.b64encode(
            hmac.new(SECRET_KEY.encode(), sign_str.encode(), hashlib.sha256).digest()).decode()
        response = requests.post(query_trans_url, headers=headers, json=json_data)
        if response.status_code != 200:
            raise TranslateException("百度翻译API请求失败")
        result = response.json()
        if result['code'] != 0:
            raise TranslateException("百度翻译API请求失败")
        if result['data']['status'] == 1:
            print(f"翻译完成, 消费金额{(result['data']['amount'] / 100):.2f}元, 下载地址{result['data']['fileSrcUrl']}")

            return True
        elif result['data']['status'] == 2:
            print("翻译失败")
            return False
        else:
            print("翻译中，请稍等...")
            time.sleep(5)


if __name__ == '__main__':
    file_path_ = 'ヒアリングシート.xlsx'
    # file_id = baidu_translate_create_job(file_path_)
    file_id = '9059c7c9f46107a89bb430573daf317c'
    # is_success = baidu_query_quote(file_id)
    # if is_success:
    #   request_id = execute_tran(file_path_, file_id)
    request_id = '6348326'
    query_trans(request_id)
